package com.cn.transfer.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.cn.transfer.common.constant.KeyConstant;
import com.cn.transfer.common.entity.SampleApplication;
import com.cn.transfer.common.entity.VvAaPartner;
import com.cn.transfer.common.entity.jiandaoyun.JdyPurchaseOrder;
import com.cn.transfer.common.entity.tplus.*;
import com.cn.transfer.common.entity.tplus.Currency;
import com.cn.transfer.common.http.ApiClient;
import com.cn.transfer.common.redis.RedisUtil;
import com.cn.transfer.common.utils.ConnmeUtils;
import com.cn.transfer.mapper.VvAaPartnerMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.Header;
import org.apache.http.message.BasicHeader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.concurrent.CompletableFuture;

/**
 * @author: weidian
 * @date: 2023/11/16 17:25
 * @Description: 索样单接口
 */
@RestController
@Slf4j
public class SampleSheetContriller {

    @Autowired
    private RedisUtil redisUtil;
    private static final String SECRET = "KPIfb04KeXBOsdfsfj3m9xDqKV9";
    private static final String DATA_CREATE = "data_create";
    private static final String DATA_UPDATE = "data_update";
    private static final String DATA_DELETE = "data_remove";

    @PostMapping("/sampleSheet")
    public String callback(@RequestParam("nonce") String nonce,
                           @RequestParam("timestamp") String timestamp,
                           @RequestHeader("x-jdy-signature") String signature,
                           @RequestBody String payload) {
        log.info("索样单申请=====" + payload);
        if (!validateSignature(nonce, payload, timestamp, signature)) {
            return "fail";
        }
        // 在这里处理消息
        handleData(payload);

        return "success";
    }

    private boolean validateSignature(String nonce, String payload, String timestamp, String signature) {
        String calculatedSignature = getSignature(nonce, payload, SECRET, timestamp);
        return calculatedSignature.equals(signature);
    }

    private String getSignature(String nonce, String payload, String secret, String timestamp) {
        return DigestUtils.sha1Hex(nonce + ":" + payload + ":" + secret + ":" + timestamp);
    }

    private void handleData(String payload) {
        // 在这里处理推送来的数据
        JSONObject payloadJSON = JSONUtil.parseObj(payload);
        String op = payloadJSON.getStr("op");
        String data = payloadJSON.getStr("data");

        if (DATA_UPDATE.equals(op)) {
            update(data);
        }
    }

    private void update(String data) {
        SampleApplication sampleApplication = JSONUtil.toBean(data, SampleApplication.class);
        Header[] headers = ConnmeUtils.createHeaders();
        Map<String, Object> parameterDelete = new HashMap<>();
        parameterDelete.put("instance_id", sampleApplication.get_id());
        parameterDelete.put("tasks_type", 1);
        String jsonSale = JSONUtil.toJsonStr(parameterDelete);
        JSONObject jdySale = ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v4/workflow/instance/get", headers, jsonSale);
        JdyPurchaseOrder jdyPurchaseOrder = JSONUtil.toBean(jdySale, JdyPurchaseOrder.class);
        Header[] headerse = new Header[4];
        headerse[0] = new BasicHeader("appKey", KeyConstant.APPKEY);
        headerse[1] = new BasicHeader("Content-Type", "application/json");
        headerse[2] = new BasicHeader("appSecret", KeyConstant.APPSECRET);
        headerse[3] = new BasicHeader("openToken", redisUtil.get("token_info").toString());

        log.info(jdyPurchaseOrder.toString());
        int size = jdyPurchaseOrder.getTasks().size() - 1;
        String flow_name = jdyPurchaseOrder.getTasks().get(size).getFlow_name();
        int staes = jdyPurchaseOrder.getTasks().get(size).getStatus();
        CompletableFuture.runAsync(() -> {
            log.info("当前的状态==" + flow_name + " " + staes);
            if (jdyPurchaseOrder.getStatus() != 2) {
                if ((Objects.equals(flow_name, "销售和客服填写寄样时间") && staes == 1) ||
                        Objects.equals(flow_name, "邮寄并最终确认（跟单？）") && staes == 1) {
                    String entries = toJsonchuku(sampleApplication);
                    ApiClient.sendPostRequestTpuls(KeyConstant.T_URL + "/tplus/api/v2/saleDelivery/Create", headerse, entries);
                } else if (Objects.equals(flow_name, "仓库确认发货数量") && staes == 0) {
                    String entries = toJsonjinhuo(sampleApplication);
                    ApiClient.sendPostRequestTpuls(KeyConstant.T_URL + "/tplus/api/v2/purchaseArrival/Create", headerse, entries);
                }
            }
        });
    }

    private String toJsonchuku(SampleApplication sampleApplication) {
        SalesDeliveryDTO salesDeliveryDTO = new SalesDeliveryDTO();
        salesDeliveryDTO.setExternalCode(IdUtil.randomUUID());
        salesDeliveryDTO.setVoucherDate(DateUtil.now());
        BusinessTypeDTO busiType = new BusinessTypeDTO();
        busiType.setCode("15");
        salesDeliveryDTO.setBusinessType(busiType);
        CustomerDTO customerDTO = new CustomerDTO();
        VvAaPartner vvAaPartner = vvAaPartnerMapper.byName(sampleApplication.getCustomer());
        customerDTO.setCode(vvAaPartner.getCode());
        salesDeliveryDTO.setCustomer(customerDTO);
        DepartmentDTO department = new DepartmentDTO();
        String s = vvAaPartnerMapper.bumCode(sampleApplication.getApplication_department().getName());
        department.setCode(s);
        salesDeliveryDTO.setDepartment(department);
        Currency currency = vvAaPartnerMapper.byBizhong(sampleApplication.getCurrency());
        CurrencyDTO currencyDTO = new CurrencyDTO();
        currencyDTO.setCode(currency.getCode());
        salesDeliveryDTO.setCurrency(currencyDTO);
        salesDeliveryDTO.setExchangeRate(currency.getExchangeRate());
        ClerkDTO clerkDTO = new ClerkDTO();
        String code = vvAaPartnerMapper.byUser(sampleApplication.getSample_applicant().getUsername());
        clerkDTO.setCode(code);
        salesDeliveryDTO.setClerk(clerkDTO);
        List<SaleDeliveryDetailDTO> saleDeliveryDetailDTOS = new ArrayList<>();
        SaleDeliveryDetailDTO deliveryDetailDTO = new SaleDeliveryDetailDTO();
        InventoryDTO inventory = new InventoryDTO();
        inventory.setCode("FY.1000.015");
        deliveryDetailDTO.setInventory(inventory);
        deliveryDetailDTO.setQuantity(sampleApplication.getSample_actual_quantity());
        deliveryDetailDTO.setOrigTaxPrice(sampleApplication.getUnit_price());
        deliveryDetailDTO.setOrigDiscountAmount(sampleApplication.getSales_amount());
        saleDeliveryDetailDTOS.add(deliveryDetailDTO);
        salesDeliveryDTO.setSaleDeliveryDetails(saleDeliveryDetailDTOS);
        InvoiceTypeDTO invoiceTypeDTO = new InvoiceTypeDTO();
        invoiceTypeDTO.setCode("02");
        salesDeliveryDTO.setInvoiceType(invoiceTypeDTO);
        Map<String, Object> dynamicProperty = new HashMap<>();
        dynamicProperty.put("dto", salesDeliveryDTO);
        return JSONUtil.toJsonStr(dynamicProperty);
    }

    @Autowired
    private VvAaPartnerMapper vvAaPartnerMapper;


    private String toJsonjinhuo(SampleApplication sampleApplication) {
        SalesOrder salesOrder = new SalesOrder();
        salesOrder.setExternalCode(IdUtil.randomUUID());
        salesOrder.setVoucherDate(DateUtil.now());
        BusinessType busiType = new BusinessType();
        busiType.setCode("01");
        salesOrder.setBusinessType(busiType);

        VvAaPartner vvAaPartner = vvAaPartnerMapper.byName(sampleApplication.getSupplier());
        Partner partner = new Partner();
        partner.setCode(vvAaPartner.getCode());
        salesOrder.setPartner(partner);
        Warehouse warehouse = new Warehouse();
        warehouse.setCode("03");
        warehouse.setName("索样仓");
        salesOrder.setWarehouse(warehouse);


        Department department = new Department();
        department.setCode("TC202408");
        salesOrder.setDepartment(department);

        List<VoucherDetail> voucherDetails = new ArrayList<VoucherDetail>();
        VoucherDetail voucherDetail = new VoucherDetail();

        Inventory inventory = new Inventory();
        inventory.setCode("FY.1000.015");
        inventory.setName("");
        voucherDetail.setInventory(inventory);
        Unit unit = new Unit();
        unit.setName("个");
        voucherDetail.setUnit(unit);
        voucherDetail.setQuantity(sampleApplication.getActual_arrival_quantity());
        voucherDetail.setOrigTaxAmount(sampleApplication.getActual_arrival_quantity() * sampleApplication.getPurchase_unit_price());
        voucherDetail.setOrigDiscountPrice(sampleApplication.getPurchase_unit_price());

        voucherDetails.add(voucherDetail);
        salesOrder.setVoucherDetails(voucherDetails);

        Map<String, Object> dynamicProperty = new HashMap<>();
        dynamicProperty.put("dto", salesOrder);
        return JSONUtil.toJsonStr(dynamicProperty);
    }

}
